package com.arcbbs.controller;

import com.arcbbs.annotation.GlobalInterceptor;
import com.arcbbs.config.WebConfig;
import com.arcbbs.entity.*;
import com.arcbbs.exception.BaseException;
import com.arcbbs.mapper.ForumArticleAttachmentMapper;
import com.arcbbs.mapper.LikeRecordMapper;
import com.arcbbs.mapper.UserInfoMapper;
import com.arcbbs.result.PageResult;
import com.arcbbs.result.Result;
import com.arcbbs.service.*;
import com.arcbbs.utils.StringTools;
import com.fasterxml.jackson.databind.util.BeanUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/forum")
public class FormArticleController {
    //    | pBoardId  | 父级板块ID                 | 否   |
//            | --------- | -------------------------- | ---- |
//            | boardId   | 板块ID                     | 否   |
//            | orderType | 0:热门1:发布时间2:最新发布 | 否   |
//            | pageNo    |                            |      |
    @Resource
    private FormArticleService formArticleService;
    @Resource
    private ForumArticleAttachmentMapper forumArticleAttachmentMapper;
    @Resource
    private LikeRecordMapper likeRecordMapper;
    @Resource
    private LikeRecordService likeRecordService;
    @Resource
    private UserInfoService userInfoService;
    @Resource
    private UserInfoMapper userInfoMapper;
    @Resource
    private ForumArticleAttachmentService forumArticleAttachmentService;
    private static final Logger logger = LoggerFactory.getLogger(FormArticleController.class);

    @RequestMapping("/loadArticle")
    public Result loadArticle(HttpSession httpSession, Integer pBoardId, Integer boardId, Integer orderType, Integer pageNo) {
        ForumArticleQuery forumArticleQuery = new ForumArticleQuery();
        forumArticleQuery.setBoardId(boardId == null || boardId == 0 ? null : boardId);
        forumArticleQuery.setpBoardId(pBoardId);
        forumArticleQuery.setPageNo(pageNo);
        SessionWebUserDto sessionWebUserDto = (SessionWebUserDto) httpSession.getAttribute("sessionKey");
        if (sessionWebUserDto != null) {
            forumArticleQuery.setCurrentUserId(sessionWebUserDto.getUserId());
        } else {
            forumArticleQuery.setStatus(1);
        }
        System.out.println(forumArticleQuery.getCurrentUserId() + "cir");

        PageResult list = formArticleService.selectbypage(forumArticleQuery, orderType);


        return Result.success(list);

    }

    @RequestMapping("/ArticleDetail")
    public Result getdetail(HttpSession httpSession, String articleId) {
        SessionWebUserDto sessionWebUserDto = (SessionWebUserDto) httpSession.getAttribute("sessionKey");
        ForumArticle forumArticle = formArticleService.getbyid(articleId);
        ForumArticleDetailVo forumArticleDetailVo = new ForumArticleDetailVo();
        ForumArticleVo forumArticleVo = new ForumArticleVo();
        BeanUtils.copyProperties(forumArticle, forumArticleVo);
        forumArticleDetailVo.setForumArticleVo(forumArticleVo);
        formArticleService.readArticle(httpSession, articleId);
        if (forumArticle.getAttachmentType() == 1) {
            List<ForumArticleAttachment> list = forumArticleAttachmentMapper.selectbyid(articleId);
            List<ForumArticleAttachmentVo> list1 = new ArrayList<>();

            if (!list.isEmpty()) {
                for (ForumArticleAttachment forumArticleAttachment : list) {
                    System.out.println(forumArticleAttachment);
                    ForumArticleAttachmentVo forumArticleAttachmentVo = new ForumArticleAttachmentVo();
                    BeanUtils.copyProperties(forumArticleAttachment, forumArticleAttachmentVo);
                    System.out.println(forumArticleAttachmentVo);
                    list1.add(forumArticleAttachmentVo);
                }
            }
            forumArticleDetailVo.setForumArticleAttachmentVo(list1);

        }
        if (sessionWebUserDto != null) {
            LikeRecord likeRecord = likeRecordMapper.getbyobjectiduseridoptype(articleId, sessionWebUserDto.getUserId(), 0);
            System.out.println(likeRecord);
            if (likeRecord != null) {
                forumArticleDetailVo.setHaveLike(true);
            }


        }
        return Result.success(forumArticleDetailVo);
    }

    @RequestMapping("/doLike")
    @GlobalInterceptor(checkLogin = true)
    public Result dolike(HttpSession httpSession, String articleId) {
        SessionWebUserDto sessionWebUserDto = (SessionWebUserDto) httpSession.getAttribute("sessionKey");
        likeRecordService.dolike(articleId, sessionWebUserDto.getUserId(), sessionWebUserDto.getNickName(), 0);
        return Result.success(true);

    }

    @Resource
    private ForumArticleAttachmentDownloadService forumArticleAttachmentDownloadService;

    @RequestMapping("/download")
    @GlobalInterceptor(checkLogin = true)
    public Result download(HttpSession httpSession, String fileId) {
        SessionWebUserDto sessionWebUserDto = (SessionWebUserDto) httpSession.getAttribute("sessionKey");
        UserInfo userInfo = userInfoMapper.selectbyuserid(sessionWebUserDto.getUserId());
        UserDownLoadInfoVo userDownLoadInfoVo = new UserDownLoadInfoVo();
        userDownLoadInfoVo.setUserIntegral(userInfo.getCurrentIntegral());
        ForumArticleAttachmentDownload articleAttachmentDownload = forumArticleAttachmentDownloadService.getbyfileidanduserid(fileId, sessionWebUserDto.getUserId());

        if (articleAttachmentDownload != null) {
            userDownLoadInfoVo.setHavedownload(true);
        }

        return Result.success(userDownLoadInfoVo);
    }

    @Resource
    private WebConfig webConfig;
    @Resource
    private FormBoardService formBoardService;

    @RequestMapping("/loadboard4post")
    public Result loadboard4post(HttpSession httpSession) {
        SessionWebUserDto sessionWebUserDto = (SessionWebUserDto) httpSession.getAttribute("sessionKey");
        Integer postType = null;
        if (!sessionWebUserDto.getIsAdmin()) {
            postType = 1;
        }
        return Result.success(formBoardService.getboardtree(postType));
    }

    @RequestMapping("/postArticle")
    @GlobalInterceptor(checkLogin = true)
    public Result postArticle(HttpSession httpSession,
                              String title,
                              Integer boardId,
                              Integer pboardId,
                              MultipartFile cover,
                              MultipartFile attachment,
                              String summary, Integer editorType, String content, String markdownContent) {

        title = StringTools.eccapeHtml(title);
        SessionWebUserDto sessionWebUserDto = (SessionWebUserDto) httpSession.getAttribute("sessionKey");
        ForumArticle forumArticle = new ForumArticle();
        forumArticle.setPBoardId(pboardId);
        forumArticle.setBoardId(boardId);
        forumArticle.setTitle(title);
        forumArticle.setContent(content);
        if (editorType == 1 && StringTools.isEmpty(markdownContent)) {
            throw new BaseException("内容不能为空");
        }
        forumArticle.setMarkdownContent(markdownContent);
        forumArticle.setEditorType(editorType);
        forumArticle.setNickName(sessionWebUserDto.getNickName());
        forumArticle.setUserId(sessionWebUserDto.getUserId());
        forumArticle.setUserIpAddress(sessionWebUserDto.getProvince());
        ForumArticleAttachment forumArticleAttachment = new ForumArticleAttachment();
        forumArticleAttachmentService.postArticle(httpSession, forumArticle, forumArticleAttachment, cover, attachment);


        return Result.success();
    }

    @RequestMapping("/attachmentDownload")
    @GlobalInterceptor(checkLogin = true)
    public void attachmentDownload(HttpSession httpSession, HttpServletRequest request, HttpServletResponse response,
                                   String fileId) {
        SessionWebUserDto sessionWebUserDto = (SessionWebUserDto) httpSession.getAttribute("sessionKey");
        ForumArticleAttachment attachment = forumArticleAttachmentService.downloadAttachment(fileId, sessionWebUserDto);
        InputStream in = null;
        OutputStream out = null;
        String downloadFileName = attachment.getFileName();
        String filePath = webConfig.getProjectFolder() + "/file/" + "attachment/" + attachment.getFilePath();
        File file = new File(filePath);
        try {
            in = new FileInputStream(file);
            out = response.getOutputStream();
            response.setContentType("application/x-msdownload; charset=UTF-8");
            // 解决中文文件名乱码问题
            if (request.getHeader("User-Agent").toLowerCase().indexOf("msie") > 0) {//IE浏览器
                downloadFileName = URLEncoder.encode(downloadFileName, "UTF-8");
            } else {
                downloadFileName = new String(downloadFileName.getBytes("UTF-8"), "ISO8859-1");
            }
            response.setHeader("Content-Disposition", "attachment;filename=\"" + downloadFileName + "\"");
            byte[] byteData = new byte[1024];
            int len = 0;
            while ((len = in.read(byteData)) != -1) {
                out.write(byteData, 0, len); // write
            }
            out.flush();
        } catch (Exception e) {
            logger.error("下载异常", e);
            throw new BaseException("下载失败");
        } finally {
            try {
                if (in != null) {
                    in.close();
                }

            } catch (IOException e) {
                logger.error("IO异常", e);
            }
            try {
                if (out != null) {
                    out.close();
                }

            } catch (IOException e) {
                logger.error("IO异常", e);
            }
        }
    }

    @RequestMapping("/articleDetailsUpdate")
    @GlobalInterceptor(checkLogin = true)
    public Result articleDetailsUpdate(HttpSession httpSession, String articleId) {
        SessionWebUserDto sessionWebUserDto = (SessionWebUserDto) httpSession.getAttribute("sessionKey");
        ForumArticle forumArticle = formArticleService.getbyid(articleId);
        if (forumArticle == null || !forumArticle.getUserId().equals(sessionWebUserDto.getUserId())) {
            throw new BaseException("文章不存在或无权编辑");
        }
        ForumArticleDetailVo forumArticleDetailVo = new ForumArticleDetailVo();
        ForumArticleVo forumArticleVo = new ForumArticleVo();
        BeanUtils.copyProperties(forumArticle, forumArticleVo);
        forumArticleDetailVo.setForumArticleVo(forumArticleVo);
        if (forumArticle.getAttachmentType() == 1) {
            List<ForumArticleAttachment> list = forumArticleAttachmentMapper.selectbyid(articleId);
            List<ForumArticleAttachmentVo> list1 = new ArrayList<>();
            for (ForumArticleAttachment forumArticleAttachment : list) {
                ForumArticleAttachmentVo forumArticleAttachmentVo = new ForumArticleAttachmentVo();
                BeanUtils.copyProperties(forumArticleAttachment, forumArticleAttachmentVo);
                list1.add(forumArticleAttachmentVo);
            }
            forumArticleDetailVo.setForumArticleAttachmentVo(list1);
        }
        return Result.success(forumArticleDetailVo);

    }

    @RequestMapping("/updateArticle")
    @GlobalInterceptor(checkLogin = true)
    public Result updateArticle(HttpSession httpSession,
                              String title,
                              Integer boardId,
                              Integer pboardId,
                              MultipartFile cover,
                              String articleId,
                              MultipartFile attachment,
                              String summary, Integer editorType, String content, String markdownContent,Integer attachmentType) {
        System.out.println(title);
        title = StringTools.eccapeHtml(title);
        SessionWebUserDto sessionWebUserDto = (SessionWebUserDto) httpSession.getAttribute("sessionKey");
        ForumArticle forumArticle = new ForumArticle();
        forumArticle.setArticleId(articleId);
        forumArticle.setPBoardId(pboardId);
        forumArticle.setBoardId(boardId);
        forumArticle.setTitle(title);
        forumArticle.setContent(content);
        forumArticle.setMarkdownContent(markdownContent);
        forumArticle.setEditorType(editorType);

        if (editorType == 1 && StringTools.isEmpty(markdownContent)) {
            throw new BaseException("内容不能为空");
        }
        forumArticle.setMarkdownContent(markdownContent);
        forumArticle.setEditorType(editorType);
        forumArticle.setNickName(sessionWebUserDto.getNickName());
        forumArticle.setUserId(sessionWebUserDto.getUserId());
        forumArticle.setUserIpAddress(sessionWebUserDto.getProvince());
        ForumArticleAttachment forumArticleAttachment=new ForumArticleAttachment();
//        forumArticleAttachmentService.postArticle(httpSession,forumArticle,forumArticleAttachment,cover,attachment);
formArticleService.updatearticle(sessionWebUserDto,forumArticle,forumArticleAttachment,cover,attachment);


        return Result.success();
    }
}
